﻿using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine.UI;


public class ConnectionManager : MonoBehaviour {


    int localPort=20591;

    static UdpClient udp;

    Thread beaconThread;

    public bool foundAutolabor=false;

    private bool lastFound=false;


    public string autolaborIP="";

    string beaconMessage="autolabor is here!";


    [SerializeField] RosConnector rosconnector;

    [SerializeField] Text displayMessage;



    void Start ()
    {
        udp = new UdpClient(localPort);
        beaconThread = new Thread(new ThreadStart(CheckBeacon));
        beaconThread.Start(); 
    }



    void OnApplicationQuit()
    {
        if (beaconThread!=null)
        {
            beaconThread.Abort();
        }
    }


    void Update()
    {

        if (lastFound==false && foundAutolabor==true)
        {
            
            OnFoundAutolabor();

            lastFound=foundAutolabor;

        }


    }

    private void CheckBeacon()
    {
        
        while(true)
        {
            
            IPEndPoint remoteEP = null;
            byte[] data = udp.Receive(ref remoteEP);
            string text = Encoding.ASCII.GetString(data);


            if (foundAutolabor==false && text.Equals(beaconMessage))
            {
                autolaborIP=remoteEP.Address.ToString();

                foundAutolabor=true;

            }

            Thread.Sleep(1000);
           
        }



    } 



    private void OnFoundAutolabor()
    {


        Debug.Log("Found Autolabor at:"+ autolaborIP);

        displayMessage.text="发现Autolabor\nIP:"+autolaborIP;

        rosconnector.ip=autolaborIP;

        //rosconnector.Connect();


   


    }





    public void OnBtnEmegryClick()
    {


        Debug.Log("OnBtnEmergyClick");

        StartCoroutine(RestartBaseLaunch());
       

    }



    IEnumerator RestartBaseLaunch()
    {

        string url="http://"+autolaborIP+":9000/task?cmd=restart&launch=createmap";

        Debug.Log("get url:"+url);

        WWW request = new WWW(url);

        yield return request;


        Debug.Log(request.text);

        // check for errors
        if (request.error == null)
        {
            Debug.Log("WWW Ok!: " + request.data);
        } else {
            Debug.Log("WWW Error: "+ request.error);
        }    


    }

}

